const Base = require('./base.js'),
	fs = require('fs'),
	path = require('path'),
	errorInfo = require('../config/error-info.js');

module.exports = class extends Base {
	/**
	 * @author: ares
	 * @date: 2019/4/15 15:39
	 * @description: 文件上传
	 * @returns {Promise.<void>}
	 */
	async uploadFileAction() {
		let self = this,
			//单文件时取this.file().file,多文件时取this.file().files
			uploadInfo = this.file().file || this.file().files,
		saveFileUrl = [];
		//如果是单文件上传,uploadInfo为对象,将其转换为数组
		if(think.isObject(uploadInfo)) uploadInfo = [uploadInfo];
		if (!uploadInfo.length) return this.fail(...errorInfo.msg1151);
		uploadInfo.forEach((file,index)=>{
			let _path = file.path,
				baseName = path.basename(_path),
				dirName = path.dirname(_path),
				newPath = path.resolve(dirName, '../') + '/' + baseName,
				savePath = newPath.replace(path.join(think.ROOT_PATH, 'www'),'');
			try {
				fs.renameSync(file.path,newPath);
			}
			catch (err){
				self.fail(...errorInfo.msg1151, `${file.name}上传失败`);
				throw err;
			}
			saveFileUrl.push(savePath);
		})
		if(saveFileUrl.length)return this.json(saveFileUrl);
		return this.fail(...errorInfo.msg1151);
	}
};
